package com.ipay.api;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.ipay.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.ipay.annotation.IgnoreAuth;
import com.ipay.core.HttpGateway;
import com.ipay.core.Param;
import com.ipay.entity.PaymentEntity;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @Description: 统一支付网关api
 * @author hacken
 * @email hacken_hu@163.com
 * @date 2017年6月21日 下午8:01:21
 * @version V1.0
 */
@RestController
@RequestMapping("/api")
public class ApiPayController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpGateway gateway;

	/**
	 * 微信 js 支付
	 * @param payment
	 * @return
	 */
	@IgnoreAuth
	@PostMapping("wxJsPay")
	public R wxJsPay(@RequestBody PaymentEntity payment) {
		System.out.println("wxJsPay====:"+JSON.toJSONString(payment));
		// 微信预支付
//		String notify_url = request.getRequestURL().toString();
//		notify_url = "http://www.***.cn/pay-wechat/payorder/jspayNotify";
		payment.setMch_create_ip(IPUtils.getIpAddr(request));
		payment.setNonce_str(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
		Map<String, String> map = MapUtils.convertObjToMap(payment);
		//移除多余的参数mchPayKey
		map.remove("mchPayKey");
		String strtosign = MapUtils.formatUrlMap(map, false, false);
		gateway.url = "https://pay.swiftpass.cn/pay/gateway";
		//TODO 查询商户相关数据
		String signstr = MD5.sign(strtosign, "&key=" + payment.getMchPayKey(), "utf-8");
		payment.setSign(signstr);
		map = MapUtils.convertObjToMap(payment);
		map.remove("mchPayKey");
		Param param = Param.create();
		param.putAll(map);
		System.out.println(JSON.toJSONString(param));
		// 银行预支付接口
		Param resultparam = gateway.post(param);
		System.out.println("resultparam----->" + resultparam);
		String status = resultparam.get("status");
		if (status.equals("0")) {// 成功
			String result_code = resultparam.get("result_code");// 业务成功结果
			if (result_code.equals("0")) {
				return R.ok().put("payinfo", resultparam);
			}
		}
		return R.error(resultparam.get("message"));
	}

	/**
	 * 银行支付
	 */
	@IgnoreAuth
	@PostMapping("pay")
	public R payment(@RequestBody PaymentEntity payment) {
		String successurl = request.getRequestURL().toString();
		successurl = successurl.substring(0, successurl.indexOf("pay-manage") + 10) + "/pay_success.html";
		payment.setMch_create_ip(IPUtils.getIpAddr(request));
		payment.setNonce_str(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
		Map<String, String> map = MapUtils.convertObjToMap(payment);
		String strtosign = MapUtils.formatUrlMap(map, false, false);
		gateway.notify_url = successurl;
		gateway.url = "https://pay.swiftpass.cn/pay/gateway";
		String signstr = MD5.sign(strtosign, "&key=9d101c97133837e13dde2d32a5054abb", "utf-8");
		payment.setSign(signstr);
		map = MapUtils.convertObjToMap(payment);
		Param param = Param.create();
		param.putAll(map);
		// 银行预支付接口
		Param resultparam = gateway.post(param);
		System.out.println(resultparam);
		String status = resultparam.get("status");
		if (status.equals("0")) {// 成功
			String result_code = resultparam.get("result_code");// 业务成功结果
			if (result_code.equals("0")) {
				return R.ok().put("payinfo", resultparam);
			}
		}
		return R.error();
	}

	/**
	 * 微信预支付
	 * 
	 * @param payment
	 * @return
	 */
	@IgnoreAuth
	@PostMapping("wxpay")
	public R wxPay(@RequestBody PaymentEntity payment) {
		// 微信预支付
		gateway.url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		Map<String, String> map = new HashMap<String, String>();
		map.clear();
		map.put("appid", payment.getAppid());
		map.put("mch_id", payment.getMch_id());
		map.put("nonce_str", RandomStringUtils.getRandomStringByLength(32));
		map.put("body", payment.getBody());
		map.put("out_trade_no", payment.getOut_trade_no());
		map.put("total_fee", payment.getTotal_fee());
		map.put("spbill_create_ip", payment.getMch_create_ip());
		map.put("notify_url", payment.getNotify_url());
		map.put("trade_type", "MWEB");
		map.put("scene_info",
				"{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"https://www.ipay.com\",\"wap_name\": \"聚合支付\"}} ");
		String strtosign = MapUtils.formatUrlMap(map, false, false);
		String signstr = MD5.sign(strtosign, "&key=9d101c97133837e13dde2d32a5054abb", "utf-8").toUpperCase();
		map.put("sign", signstr);
		Param param = Param.create();
		param.putAll(map);
		// 微信支付接口调用
		Param wxresult = gateway.post(param);
		System.out.println(wxresult.toString());
		String return_code = wxresult.get("return_code");// SUCCESS
		String result_code = wxresult.get("result_code");// 交易是否成功判断码 SUCCESS
		System.out.println("return_code:"+return_code+"  result_code:"+result_code);
		return R.ok().put("wxresult", wxresult);
	}

	/**
	 * 支付宝支付
	 * 
	 * @param payment
	 * @return
	 */
	@IgnoreAuth
	@PostMapping("aliJsPay")
	public R aliJsPay(@RequestBody PaymentEntity payment) {
		// 支付宝支付
		gateway.url = "https://pay.swiftpass.cn/pay/gateway";
		Map<String, String> map = MapUtils.convertObjToMap(payment);
		String strtosign = MapUtils.formatUrlMap(map, false, false);
		String signstr = MD5.sign(strtosign, "&key=58bb7db599afc86ea7f7b262c32ff42f", "utf-8").toUpperCase();
		map.put("sign", signstr);
		Param param = Param.create();
		param.putAll(map);
		// 微信支付接口调用
		Param wxresult = gateway.post(param);
		System.out.println(wxresult.toString());
		String return_code = wxresult.get("return_code");// SUCCESS
		String result_code = wxresult.get("result_code");// 交易是否成功判断码 SUCCESS
		System.out.println("return_code:"+return_code+"  result_code:"+result_code);
		return R.ok().put("wxresult", wxresult);
	}

	/**
	 * 退款查询
	 */
	@IgnoreAuth
	@PostMapping("refundquery")
	public R refundquery(@RequestBody PaymentEntity payment) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("service", "unified.trade.refundquery");
		map.put("mch_id", payment.getMch_id());
		map.put("out_trade_no", payment.getOut_trade_no());
		String strtosign = MapUtils.formatUrlMap(map, false, false);
		String signstr = MD5.sign(strtosign, "&key=9d101c97133837e13dde2d32a5054abb", "utf-8");

		map.put("nonce_str", RandomStringUtils.getRandomStringByLength(32));
		map.put("sign", signstr);
		Param param = Param.create();
		param.putAll(map);

		gateway.url = "https://pay.swiftpass.cn/pay/gateway";
		Param resultparam = gateway.post(param);
		System.out.println(resultparam.toString());

		return R.ok();
	}
}
